#include <memory>
#include "Reactor.hpp"
#include "Listener.hpp"
#include "Cal.hpp"
#include "Protocol.hpp"

static void Usage(char *arg)
{
    std::cerr << "Usage: " << arg << " port" << std::endl;
}

// ./server port
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(USAGE_ERR);
    }
    uint16_t port = std::stoi(argv[1]);
    InetAddr addr(port);

    // 1.创建业务对象
    Cal cal;

    // 2.创建协议对象，绑定业务方法
    std::shared_ptr<Protocol> protocol = std::make_shared<Protocol>(
        [&cal](const Request &req) -> Response
        {
            return cal.Calculate(req);
        });

    // 3.创建Listensock的Connection，注册绑定协议回调方法
    std::shared_ptr<Connection> conn = std::make_shared<Listener>(addr);
    conn->RegisterHandler([&protocol](std::string &inbuffer) -> std::string
                          {
            std::string resp;
            while (true)
            {
                // 执行回调，截取报文（截取多个报文）
                // 反序列化，执行具体业务回调，序列化，添加报头，返回once
                std::string once = protocol->Execute(inbuffer);
                if (once == std::string())
                    break;
                resp += once;
            }
            return resp; });

    // 4.创建Reactor，添加Connection(Listensock)
    std::unique_ptr<Reactor> R = std::make_unique<Reactor>();
    R->AddConnection(conn);

    R->Loop();

    return 0;
}